<template>
  <div>
    <span v-if="boxType === 'view'" style="color: #606266;">{{ formData[prop] }}</span>
    <avue-input-tree v-else v-model="formData[fieldKey || prop]" :dic="data" :placeholder="`请选择 ` + label" filterable
      clearable :props="defaultProps" defaultExpandAll :disabled="disabled" v-bind="comProps"
      :nodeClick="handleNodeClick" @clear="handleClear"></avue-input-tree>
  </div>
</template>

<script setup>
// 自带的默认参照类型
import { watch } from 'vue'
import referTypeMap from './BasicCrudInputTree.js'
import request from '@/utils/request.js'
const props = defineProps({
  disabled: Boolean,
  boxType: String,
  curForm: {
    type: Object,
    default: () => ({})
  },
  label: String,
  prop: String,
  referUrl: String,
  referType: String,
  fieldKey: String,
  comProps: {
    type: Object,
    default: () => ({})
  },
  saveFieldMap: {
    type: Object,
    default: () => ({})
  },
  // 请求参数映射
  paramsFielsMap: {
    type: Object,
    default: () => ({})
  },
  // 是否自动获取,有paramsFielsMap经常为false
  autoLoad: {
    type: Boolean,
    default: true
  },
  change: Function
})

const defaultProps = {
  label: 'name',
  value: 'id',
  children: 'children'
}
const formData = defineModel('form', {
  type: Object,
  default: () => ({})
})


const data = ref([])

const getReferData = async () => {
  // 默认以referUrl为准创建请求方法
  let requestFun = () => {
    return request({
      url: props.referUrl,
      method: 'get',
    })
  }
  if (props.referType) {
    requestFun = referTypeMap[props.referType]
  }
  let params = {}
  for (const key in props.paramsFielsMap) {
    if (Object.prototype.hasOwnProperty.call(props.paramsFielsMap, key)) {
      const element = props.paramsFielsMap[key];
      params[key] = formData.value[element]
    }
  }
  const res = await requestFun(params)
  data.value = res || []
}
if (props.autoLoad) {
  getReferData()
}

// 设置监听
const setWatch = () => {
  let watchHandlerList = []
  for (const key in props.paramsFielsMap) {
    if (Object.prototype.hasOwnProperty.call(props.paramsFielsMap, key)) {
      const element = props.paramsFielsMap[key];
      watchHandlerList.push(() => formData.value[element])
      watch(watchHandlerList, () => {
        getReferData()
      })
    }
  }
}
setWatch()

// 节点选中
const handleNodeClick = (data) => {
  for (const key in props.saveFieldMap) {
    if (Object.prototype.hasOwnProperty.call(props.saveFieldMap, key)) {
      const val = props.saveFieldMap[key];
      formData.value[key] = data[val]
    }
  }
  props.change && props.change(formData.value)
}
// 数据清除
const handleClear = () => {
  for (const key in props.saveFieldMap) {
    if (Object.prototype.hasOwnProperty.call(props.saveFieldMap, key)) {
      formData.value[key] = undefined
    }
  }
  props.change && props.change(formData.value)
}

watch(() => props.curForm, (val) => {
  formData.value = val
}, { deep: true, immediate: true })
</script>

<style lang='scss' scoped></style>